<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\facade\WeChatMini;
use app\common\model\ProductCate;
use app\common\model\ProductSearch;
use app\common\model\SpecItem;
use think\facade\Cache;
use think\facade\Event;
use think\facade\Log;
use think\Response;
use app\common\tool\Result;
use app\common\model\ProductEvaluate;
use app\common\model\ProductService;
use app\common\model\ProductSpecData;
use app\common\model\ProductSpecValue;
use app\common\model\UserCollectBusiness;
use app\common\model\UserCollectProduct;
use app\common\model\Product as ProductModel;

class Product extends Base
{
    /**
     * 校验会员级别
     * @param int $cate_1
     * @param string $type
     * @return Response
     */
    public function checkUserLevel(int $cate_1 = 0, string $type = 'cate', string $port = ''): Response
    {
        return Result::success('success');
    }


    /**
     * @return Response
     */
    public function checkContract(): Response
    {
        return Result::success('success', ['open'=>1]);

    }

    /**
     * @return Response
     * 统一获取商品接口
     */
    public function index(): Response
    {
        try {
            $param = $this->request->get();
            $map = ['is_del' => 0, 'status' => 1, 'examine_status' => 2];
            $map['leader'] = 0;
            //限时活动
            if (isset($param['activity']) && $param['activity'] == 1) {
                $map['activity'] = 1;
            }
            //热门推荐
            if (isset($param['pick']) && $param['pick'] == 1) {
                $map['pick'] = 1;
            }
            //今日新品
            if (isset($param['new']) && $param['new'] == 1) {
                $map['new'] = 1;
            }
            //分类
            $key = ['cate_1', 'cate_2', 'cate_3'];
            foreach ($key as $v) {
                if (isset($param[$v])) {
                    $map[$v] = $param[$v];
                }
            }

            if($this->user && $this->user->syn_level > 4){
                $map['leader'] = 1;
            }
            //关键字筛选
            $like = [];
            if (isset($param['keyword']) && $param['keyword']) {
                $like = ['field' => 'title', 'keyword' => $param['keyword']];
                if($this->user){
                    Event::trigger('ProductSearch', ['keyword'=>$param['keyword'], 'uid'=>$this->user->id]);
                }
            }
            //排序
            $defaultSort = ['key' => 'sort', 'value' => 'asc'];
            if (isset($param['sortKey']) && $param['sortKey']) {
                $defaultSort['key'] = $param['sortKey'];
                $defaultSort['value'] = isset($param['sortVal']) ? $param['sortVal'] : 'asc';
            }
            //获取店铺商品
            if (isset($param['business_id']) && $param['business_id']) {
                $map['business_id'] = $param['business_id'];
            }
            //店铺推荐
            if (isset($param['business_pick']) && $param['business_pick'] == 1) {
                $map['business_pick'] = 1;
            }
            $list = ProductModel::getPageList($map, 'id,title,price,vip_price,icon,business_id,discount_open', $this->getPage(),
                $this->getLimit(), false, ['business'], '', $defaultSort, $like);
            return Result::fastReturn($list);

        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * 热门搜索
     * @return Response
     */
    public function hotSearch(): Response
    {
        try {
            $list = ProductSearch::where('is_del', 0)->field('keyword')->order('hot', 'desc')->limit(15)->select();
            return Result::success('success', $list);
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * @param int $pid
     * @param int $business_id
     * @return Response
     */
    public function cate($pid = 0, $business_id=0): Response
    {
        $this->verifyToken();
        try {
            if(0 == $pid){
                $cats = ProductCate::getCate($pid, $business_id);
                $cats = array_column($cats->toArray(), null, 'id');

                $cats = array_values($cats);
                return Result::success('success', $cats);
            }else{
                return Result::success('success', ProductCate::getCate($pid));
            }

        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * @return Response
     */
    public function read($id): Response
    {
        try {
            $this->verifyToken();

            $where['status'] = 1;
            $where['is_del'] = 0;
            if($scene = $this->request->param('scene')){
                $where['share_scene'] = $scene;
            }else{
                $where['id'] = $id;
            }

            $info = ProductModel::where($where)
                ->with('business')
                ->field('id,business_id,cate_1,cate_2,title,images,price,vip_price,sales,stock,discount_open,
                currency,chain_bean,love_bean,vip_integ,red_coin,service,content_text,content_images,freight,give_discount_amount,video_link')
                ->find();
            if (empty($info)) return Result::fail('商品不存在');

            $info->business->all_product = ProductModel::where(['business_id' => $info->business_id, 'status' => 1, 'examine_status' => 2])->count();
            //是否关注店铺
            $info->business->is_fans = $this->user ? UserCollectBusiness::isCollect($this->user->id, $info->business_id) : 0;
            //是否收藏商品
            $info->is_collect = $this->user ? UserCollectProduct::isCollect($this->user->id, $info->id) : 0;
            //$info->discount = $info->discount_open == 1 ? $info->give_discount_amount : '0.00';
            $info->discount = '0.00';
            if($info->discount_open == 1){
                $info->discount = ProductModel::where('give_discount_pid', $info->id)->value('give_discount_amount');
            }
            $info->serviceText = ProductService::where(['is_del' => 0, 'status' => 1])
                ->whereIn('id', $info['service'])
                ->field('id,title,explain')->select();
            $info->spec = ProductSpecData::getSpecData($info->id, true);
            //商品评价
            $info->evaluate = ProductEvaluate::getProductEvaluate($info->id, 2);
            //商品评价条数
            $info->evaluateCount = ProductEvaluate::getProductEvaluateCount($info->id);

            $info->is_buy = 1;
            if($info->cate_1 == 9){
                if(!$this->user || $this->user->level_id < 3){
                    $info->is_buy = 0;
                }
            }

            if ($this->user) Event::trigger('ProductView', ['uid' => $this->user->id, 'pid' => $info->id]);
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试:' . $e->getMessage());
        }
    }

    /**
     * @param $pid - 商品ID
     * @param $sku_id - sku组合ID
     * @return Response
     * 获取商品组合sku相关信息
     */
    public function getSpecItemInfo($pid, $sku_id): Response
    {
        try {
            $info = ProductSpecValue::where(['sku_id' => $sku_id, 'pid' => $pid])
                ->field('id,sku_id,vip_price,price,icon,stock')->find();
            if (empty($info)) {
                return Result::fail('未查询到当前规格信息，请检查sku_id');
            }
            $info->sku_name = SpecItem::getSpecItemName($info->sku_id);
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * @return Response
     * 收藏/取消收藏商品
     */
    public function collect(): Response
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(
                $param['type'] == 1 ?
                    UserCollectProduct::add($this->user->id, $param['id']) :
                    UserCollectProduct::cancel($param['id'], $this->user->id));
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * 评价列表
     * @return Response
     */
    public function evaluateList(): Response
    {
        try {
            $param = $this->request->get();
            $id = $param['id'];
            $type = $param['type'] ?? 0;

            $listRows = [
                'page'      => $this->getPage(),
                'list_rows' => $this->getLimit()
            ];
            $sql = ProductEvaluate::with(['user'])->where(['pid' => $id]);
            $count['all'] = $sql->count();
            $count['images'] = $sql->where('images', '<>', '')->count();
            $sql->removeWhereField('images');
            $count['good'] = $sql->where('score', '>', 3)->count();
            $sql->removeWhereField('score');
            $count['middle'] = $sql->where('score', 3)->count();
            $sql->removeWhereField('score');
            $count['bad'] = $sql->where('score', '<', 3)->count();
            $sql->removeWhereField('score');
            if ($type == 1) {
                $sql->where('images', '<>', '');
            } elseif ($type == 2) {
                $sql->where('score', '>', 3);
            } elseif ($type == 3) {
                $sql->where('score', 3);
            } elseif ($type == 4) {
                $sql->where('score', '<', 3);
            }
            $list = $sql->field('id,pid,uid,content,images,score,create_time,status,business_id,order_id,order_product_id,reply_content,reply_time,reply_admin_id,reply_admin_name')
                ->order('create_time', 'desc')->paginate($listRows);

            $result = ['code' => 1, 'msg' => 'success', 'data' => ['data' => $list->items(), 'count' => $count]];
            return Result::fastReturn($result);
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    public function shareCode()
    {
        $product_id = $this->request->param('product_id');
        if(!$product = ProductModel::where('id', $product_id)->field('id,share_code')->find()){
            return Result::fail('商品不存在');
        }

        if(!$product->share_code){
            $share_scene = date("YmdHis").mt_rand(1000,9999).'_'.$product_id;
            $scene = $share_scene.',0';
            $savePath = '/uploads/productQrcode/';
            $code = WeChatMini::getMiniScene($scene, 'detail/pages/index/index', $savePath);

            if($code){
                $product->share_code = $code;
                $product->share_scene = $share_scene;
                $product->save();
            }else{
                return Result::fail('获取商品分享码失败');
            }
        }

        return Result::success('success', ['share_code'=>$product->share_code]);

    }

}

